#include <stdio.h>
#include <stdlib.h>

typedef char DataType;

typedef struct node {
    DataType data;
    struct node *next;
} LinkNode;

typedef LinkNode LinkList;


LinkList *init() {

    LinkList *head = (LinkList *) malloc(sizeof(LinkNode));
    head->data = '0';

    DataType ch;

    LinkNode *last = head;

    while ((ch = getchar()) != '\n') {

        LinkNode *p = (LinkNode *) malloc(sizeof(LinkNode));

        p->next = NULL;
        p->data = ch;

        last->next = p;
        last = p;
    }

    return head;
}

/**
 * 将指定元素插入到链表中
 * @param list
 * @param index
 * @param value
 */
void add(LinkList *list, int index, DataType value) {

    int i = 0;
    LinkNode *item = list;

    while (item != NULL && index - 1 > i) {
        item = list->next;
        i++;
    }

    if (item == NULL) {
        printf("ERROR \n");
        return;
    }

    LinkNode *p = (LinkNode *) malloc(sizeof(LinkNode));
    p->data = value;
    p->next = item->next;

    item->next = p;
}

LinkNode *getIndex(LinkList *list, int index) {

    // 当前指向第一个节点
    LinkNode *p = list->next;
    int i = 1;

    while (p != NULL && index > i) {
        p = p->next;
        i++;
    }

    return p;
}

DataType deleteIndex(LinkList *list, int index) {

    int i = 0;
    LinkNode *item = list;

    while (item != NULL && index - 1 > i) {
        i++;
        item = item->next;
    }

    if (NULL == item) {
        printf("index error");
        return '0';
    }

    LinkNode *freeNode = item->next;
    DataType data = freeNode->data;

    item->next = freeNode->next;

    free(freeNode);

    return data;
}

LinkNode *getValue(LinkList *list, DataType value) {

    LinkNode *p = list->next;

    while (p != NULL && p->data != value) {
        p = p->next;
    }
    return p;
}


void toString(LinkList *list) {

    LinkNode *top = list->next;
    printf("[");

    while (top != NULL) {
        printf("%c,", top->data);
        top = top->next;
    }
    printf("]\n");
}


int main() {
    printf("please input some key example:abcde \n");

    LinkList *list = init();
    toString(list);

    LinkNode *item = getIndex(list, 5);
    printf("getIndex 5 value=%c\n", item == NULL ? 'N' : item->data);

    LinkNode *value = getValue(list, 'c');
    printf("getValue c value=%c\n", value == NULL ? 'N' : value->data);


    add(list, 1, 'z');
    toString(list);

    deleteIndex(list, 1);
    toString(list);

    return 0;
}
